package com.atao.baokede.service.serviceImpl;

import com.atao.baokede.mapper.AddressMapper;
import com.atao.baokede.pojo.Address;
import com.atao.baokede.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import com.atao.baokede.utils.ThreadLocalUtil;
import java.util.Map;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public void addAddress(Address address) {
        address.setCreateTime(LocalDateTime.now());
        address.setUpdateTime(LocalDateTime.now());
        // 如果是默认地址，先取消该用户其他默认地址
        if ("1".equals(address.getIsDefault())) {
            addressMapper.cancelDefaultAddress(address.getUserId());
        }
        addressMapper.addAddress(address);
    }

    @Override
    public void updateAddress(Address address) {
        address.setUpdateTime(LocalDateTime.now());
        // 如果设置为默认地址，先取消该用户其他默认地址
        if ("1".equals(address.getIsDefault())) {
            addressMapper.cancelDefaultAddress(address.getUserId());
        }
        addressMapper.updateAddress(address);
    }

    @Override
    public void deleteAddress(Long id, Long userId) {
        addressMapper.deleteAddress(id);
    }

    @Override
    public List<Address> getAddressesByUserId(Long userId) {
        return addressMapper.getAddressesByUserId(userId);
    }

    @Override
    public void setDefaultAddress(Long id, Long userId) {
        // 先取消所有默认地址
        addressMapper.cancelDefaultAddress(userId);
        // 设置当前地址为默认
        addressMapper.setDefaultAddress(id, userId);
    }

    // 新增方法实现
    @Override
    public void addAddressWithCurrentUser(Address address) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Long userId = ((Number) map.get("id")).longValue();
        address.setUserId(userId);
        addAddress(address);
    }

    @Override
    public void updateAddressWithCurrentUser(Address address) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Long userId = ((Number) map.get("id")).longValue();
        address.setUserId(userId);
        updateAddress(address);
    }

    @Override
    public void deleteAddressWithCurrentUser(Long id) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Long userId = ((Number) map.get("id")).longValue();
        deleteAddress(id, userId);
    }

    @Override
    public List<Address> getAddressesWithCurrentUser() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Long userId = ((Number) map.get("id")).longValue();
        return getAddressesByUserId(userId);
    }

    @Override
    public void setDefaultAddressWithCurrentUser(Long id) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Long userId = ((Number) map.get("id")).longValue();
        setDefaultAddress(id, userId);
    }
}